package com.example.springsecuritydemo.service;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Classname: UserDetailsServiceImpl
 * @Description: UserDetailsService实现类
 * @Date: 2021/3/15 20:46
 * @Created: by Wang Xu
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private PasswordEncoder passwordEncoder;

    /**
     * @description: 自定义登录逻辑 
     * @param: [username] 
     * @return: org.springframework.security.core.userdetails.UserDetails 
     * @author: wangxu
     * @date: 2021/3/15 20:55
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        System.out.println("执行了loadUserByUsername方法！！！！！！！");


        // 1.查询数据库，判断用户名是否存在，如果不存在就抛出UsernameNotFoundException异常
        if (!"admin".equals(username)) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        // 2.把查询出来的密码(注册时候已经加密过的)进行解析，或者把密码直接放入构造方法
        String password = passwordEncoder.encode("123");

        return new User(username,
                password,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_abc,/main.html,/insert,/delete")); // 有admin normal权限   abc角色
    }
}
